﻿using FunnyArts.JSAdapter.Attri;
using FunnyArts.JSAdapter.Inter;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace FunnyArts.Plugin.HisHcApi
{
    [JSObject(Name = "App")]
    public class HisHcApiApp : IJavaScriptObject
    {
        /// <summary>
        /// 获取IP地址
        /// </summary>
        /// <returns></returns>
        [JSFunction]
        public string getIPAddress()
        {
            string hostName = Dns.GetHostName();
            IPAddress[] addresses = Dns.GetHostAddresses(hostName);
            // 尝试获取 IPv4 地址
            IPAddress ipv4Address = addresses.FirstOrDefault(ip => ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork);

            // 如果没有找到 IPv4 地址，则获取 IPv6 地址
            if (ipv4Address == null)
            {
                ipv4Address = addresses.FirstOrDefault(ip => ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6);
            }
            return ipv4Address.ToString();
        }
        /// <summary>
        /// 获取计算机名称
        /// </summary>
        /// <returns></returns>
        [JSFunction]
        public string getComputerName()
        {
            return Environment.MachineName;
        }
        /// <summary>
        /// 获取本地配置
        /// </summary>
        /// <returns></returns>
        [JSFunction]
        public string getPackageInfo()
        {
            return "";
        }
        /// <summary>
        /// 获取mac地址
        /// </summary>
        /// <returns></returns>
        [JSFunction]
        public string getMAC()
        {
            return GetMacAddress(getIPAddress())?.ToString();
        }

        private PhysicalAddress GetMacAddress(string ipAddress)
        {
            try
            {
                IPAddress targetIp = IPAddress.Parse(ipAddress);
                NetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();

                foreach (NetworkInterface networkInterface in networkInterfaces)
                {
                    if (networkInterface.OperationalStatus == OperationalStatus.Up)
                    {
                        IPInterfaceProperties ipProperties = networkInterface.GetIPProperties();

                        foreach (UnicastIPAddressInformation ip in ipProperties.UnicastAddresses)
                        {
                            if (ip.Address.AddressFamily == AddressFamily.InterNetwork && ip.Address.Equals(targetIp))
                            {
                                return networkInterface.GetPhysicalAddress();
                            }
                        }
                    }
                }

                return null;
            }
            catch (Exception)
            {
                return null;
            }
        }
    }
}
